package cn.ffcs.bpmpvc.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.echoice.spring.SpringContextUtil;
import org.echoice.util.DateUtil;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ffcs.bpmpvc.services.bean.ConfigBean;
import cn.ffcs.bpmpvc.web.util.UserContextUtil;
import cn.ffcs.common.dao.AttachDAO;
import cn.ffcs.common.model.Attach;

public class FileUtil {
	public static void fileDown(String fileName,HttpServletResponse response) throws UnsupportedEncodingException{
		fileDown(fileName,null,response);
	}

	public static void fileDown(String fileName,String showName,HttpServletResponse response) throws UnsupportedEncodingException{
		File file=new File(fileName);
		if(StringUtils.isBlank(showName)){
			showName=file.getName();
		}
		if(file.exists()){
			response.setContentType("application/stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""+ URLEncoder.encode(showName,"UTF-8")+ "\"");
			try {
				OutputStream os = response.getOutputStream();
				BufferedOutputStream osbf=new BufferedOutputStream(os);				
				FileInputStream fis = new java.io.FileInputStream(file);
				BufferedInputStream fisBf=new BufferedInputStream(fis);
				byte[] b = new byte[1024];
				int i = 0;
				while ((i = fisBf.read(b)) > 0) {
					osbf.write(b, 0, i);					
				}
				fisBf.close();
				fis.close();
				osbf.flush();
				osbf.close();
				os.flush();
				os.close();
			} catch (Exception e) {
			}
		}
	}
	
	/**
	 * 通用文件保存（至文件系统）
	 * @param request
	 * @param attachDAO
	 * @param savePath
	 * @param type
	 * @param appId
	 * @throws IOException
	 */
	public static void saveAttaFiles(HttpServletRequest request,String type,String appId) throws IOException{
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator temp=multipartRequest.getFileNames();
		Attach attach=null;
		String savePath=getConfigBean().getUploadFilePath();
		String fold=DateUtil.format(new Date(), "yyyy-MM");
		String finalPath=savePath+fold+"/";
		File filePath=new File(finalPath);
		if(!filePath.exists()){
			filePath.mkdirs();
		}
		String fileExt=null;
		String fileName =null;
		String fileShorName=null;
		while(temp.hasNext()){
			String element = (String) temp.next();
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(element);
			if(StringUtils.isNotBlank(file.getOriginalFilename())){
				fileExt = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
				fileShorName = StringUtils.substringBeforeLast(file.getOriginalFilename(), ".");
				
				attach=new Attach();
				attach.setSaveType(2);
				attach.setFileType("FILE");
				attach.setPrefix(fileExt);
				attach.setName(file.getOriginalFilename());
				
				attach.setRefEntity(type);
				attach.setRefEntityID(appId);
				attach.setBegin(new Date());
				attach.setIsPublish(1);
				attach.setCreator(UserContextUtil.getUserContext(request).getCurrUser().getUserID());
				
				attach.setEnd(FlowContextUtil.getEndDate());
				
				getAttachDao().save(attach);
				
				fileName = fileShorName + "-" + attach.getId() + "." + fileExt;
				attach.setFullName(fileName);
				attach.setRelativePath(fold);
				getAttachDao().update(attach);
				
				FileCopyUtils.copy(file.getBytes(), new File(finalPath+fileName));
			}
		}
	}
	
	public static void saveOneAttaFiles(HttpServletRequest request,CommonsMultipartFile file,String refEntity,String fileType,String appId) throws IOException{
		if(StringUtils.isNotBlank(file.getOriginalFilename())){
			String savePath=getConfigBean().getUploadFilePath();
			String fold=DateUtil.format(new Date(), "yyyy-MM");
			String finalPath=savePath+fold+"/";
			File filePath=new File(finalPath);
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			
			String fileExt = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String fileShorName = StringUtils.substringBeforeLast(file.getOriginalFilename(), ".");
			
			Attach attach=new Attach();
			attach.setSaveType(2);
			if(StringUtils.isNotBlank(fileType)){
				attach.setFileType(fileType);
			}else{
				attach.setFileType("FILE");
			}
			attach.setPrefix(fileExt);
			attach.setName(file.getOriginalFilename());
			
			attach.setRefEntity(refEntity);
			attach.setRefEntityID(appId);
			attach.setBegin(new Date());
			attach.setIsPublish(1);
			attach.setCreator(UserContextUtil.getUserContext(request).getCurrUser().getUserID());
			
			attach.setEnd(FlowContextUtil.getEndDate());
			
			getAttachDao().save(attach);
			
			String fileName = fileShorName + "-" + attach.getId() + "." + fileExt;
			attach.setFullName(fileName);
			attach.setRelativePath(fold);
			getAttachDao().update(attach);
			
			FileCopyUtils.copy(file.getBytes(), new File(finalPath+fileName));
		}
	}
	/**
	 * 公用文件下载
	 * @param attachId
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	public static void downCommnAttachFile(String attachId,HttpServletResponse response) throws UnsupportedEncodingException{
		AttachDAO<Attach> attachDAO=getAttachDao();
		ConfigBean configBean=(ConfigBean)SpringContextUtil.getBean("configBean");
		Attach attach=attachDAO.findById(Integer.valueOf(attachId));
		String file=configBean.getUploadFilePath()+attach.getRelativePath()+"/"+attach.getFullName();
		fileDown(file,attach.getName(),response);
	}
	
	private static AttachDAO<Attach> getAttachDao(){
		AttachDAO<Attach> attachDAO=(AttachDAO<Attach>)SpringContextUtil.getBean("AttachDAO");
		return attachDAO;
	}
	
	private static ConfigBean getConfigBean(){
		ConfigBean configBean=(ConfigBean)SpringContextUtil.getBean("configBean");
		return configBean;
	}
	/**
	 * 公用文件下载
	 * @param attachId
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	public static void downCommnAttachFile(Attach attach,HttpServletResponse response) throws UnsupportedEncodingException{
		ConfigBean configBean=(ConfigBean)SpringContextUtil.getBean("configBean");
		String file=configBean.getUploadFilePath()+attach.getRelativePath()+"/"+attach.getFullName();
		fileDown(file,attach.getName(),response);
	}
}
